﻿using System.Threading.Tasks;
using System.IO;
using System.Text;
using Bolai.Event;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using Random = System.Random;

namespace HsVoice
{
    public class HsSynthHandle
    {
        /*
           byte[] 数组转 float[] ，float[] 转 AudioClip 死活转化不了，我草了
           先这样吧，写入后读取。
        */

        private FileStream fs;
        private StreamWriter sw;
        private  Random random = new Random();
        
        private string taskuid;
        public int taskid;
        private string writePath
        {
            get
            {
                if (Directory.Exists($"{ UnityEngine.Application.persistentDataPath}/voice/") == false)
                    Directory.CreateDirectory($"{UnityEngine.Application.persistentDataPath}/voice/");
                return $"{UnityEngine.Application.persistentDataPath}/voice/";
            }
        }
        
        //写入
        public void Write(byte[] data)
        {
            using ( FileStream fs1 = new FileStream($"{writePath}/{taskid}.mp3", FileMode.Append))
            {
                fs1.Write(data);
            }
        }

        public async void LoadAudio()
        {
            LoadAudio(taskid);
        }
        public async void LoadAudio(int id)
        {
            DoLoadAudio(id.ToString());
        }
        public void NewTaskUid()
        {
            taskuid = HsTools.NewTaskUid();
        }
        
        //释放流
        public  void DisposeStream()
        {
   

        }
        
        private async UniTask DoLoadAudio(string aName)
        {

            string path = HsTools.PlatformMP3Path(aName);
            using (UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(path,UnityEngine.AudioType.MPEG))
            {
                await uwr.SendWebRequest();
                var audio = DownloadHandlerAudioClip.GetContent(uwr);
                ApiBucket.Game.uevent.Call(EventCode.Voice,audio);
            }
        }
    
    }
}